local cjson     = require "cjson"
local string    = require "string"
local table_new = require "table.new"
local table     = require "table"
local jwt       = require "resty.jwt"
local redis     = require "redis"
local keysutils = require "keysutils"
local utilsdate = require "utilsdate"
local utils     = require "utils"
local global    = require "global"

require "functions"

local _M={}

function _M.access()
    local arg=ngx.req.get_uri_args()
    local secret = string.format("%s-%s", global.get_appname(), global.get_appversion())
    local jwtval = arg.jwt
    if jwtval then
        local jwtobj = jwt:verify(secret,jwtval)
        if not jwtobj or not jwtobj.payload or not jwtobj.payload.token or not jwtobj.payload.id then
            ngx.say(cjson.encode({errcode=401,errmsg='参数解析错误'}))
            ngx.exit(401)
            return
        end
        local rediscli = redis:new(global.get_redis_conf())
        -- if not DEBUG then
        --     local key = keysutils.get_admin_user_token(jwtobj.payload.id)
        --     local oldtoken = rediscli:get(key)
        --     if oldtoken~=jwtobj.payload.token then
        --         ngx.say(cjson.encode({errcode=400,errmsg='安全检测中...',oldtoken=oldtoken,curtoken=jwtobj.payload.token}))
        --         ngx.exit(401)
        --         return
        --     end
        -- end

        local args = ngx.req.get_uri_args()
        args.id = jwtobj.payload.id
        ngx.req.set_uri_args(args)
    end
end

return _M
